import tkinter
import tkinter.filedialog
import tkinter.messagebox
try:
    from PIL import Image, ImageDraw
except ModuleNotFoundError:
    Image = None
    ImageDraw = None
from graphic import basic as GUIBasic
from swap import data as SwapData
from data.config import W


def menu(master):
    menu_bar = tkinter.Menu()
    master['menu'] = menu_bar

    file_menu = tkinter.Menu(tearoff=0)
    menu_bar.add_cascade(label='File', menu=file_menu)

    def open_command():
        open_target = tkinter.filedialog.askopenfile(initialdir='./example/', filetypes=[('TXT', '*.txt')])
        try:
            target_read = open_target.read()
            open_target.close()
            target_data = eval(target_read)
            GUIBasic.clear_paper()
            for unit in target_data:
                SwapData.current_color = unit[2]
                SwapData.pixel_board[unit[1]][unit[0]].click()
        except AttributeError:  # Cancel
            pass

    file_menu.add_command(label='Open', command=open_command)

    def save_command():
        save_target = tkinter.filedialog.asksaveasfile(defaultextension='.txt', filetypes=[('TXT', '*.txt')])
        try:
            save_target.write(str(SwapData.data))
            save_target.close()
        except AttributeError:  # Cancel
            pass

    file_menu.add_command(label='Save', command=save_command)

    def export_command():
        if Image is None or ImageDraw is None:  # No PIL(Pillow) module
            msg = """PIL(Pillow) not found on this device.
            
Use command [pip install pillow] to install PIL module."""
            tkinter.messagebox.showinfo(title="Module Missed", message=msg)
            return None
        save_file_name = tkinter.filedialog.asksaveasfilename(defaultextension='.png', filetypes=[('PNG', '*.png')])
        try:
            max_x, max_y = 0, 0
            for unit in SwapData.data:
                if unit[0] > max_x:
                    max_x = unit[0]
                if unit[1] > max_y:
                    max_y = unit[1]
            w = 5 * W
            opt = Image.new('RGBA', (max_x * w + w, max_y * w + w))
            target = ImageDraw.Draw(opt)
            for unit in SwapData.data:
                target.rectangle([(unit[0] * w, unit[1] * w), (unit[0] * w + w, unit[1] * w + w)], fill=unit[2])
            opt.save(save_file_name)
        except ValueError:  # Cancel
            pass

    file_menu.add_command(label='Export', command=export_command)
